/**
 * Test algorithms for JettHoughts
 * 
 * Created 12/02/2012
 * 
 * @author Vasili Svirski
 * @version 0.01
 */

package com.jetthoughts.algorithms;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Class to search pattern text in mask file.
 * 
 */
public class FileByMask {

	private static String fileMask = "";
	private static String pattern = "";
	private static String resultFile = null;

	/**
	 * List of files from directory
	 * @param dir - current directory
	 */
	private static void listFilesInDirectory(File dir) {
		File[] files = dir.listFiles();

		if (files != null) {
			for (File f : files) {
				if (f.isDirectory()) {
					listFilesInDirectory(f);
				}
				else {
					if (f.getName().toString().contains(fileMask)){
						if (textFind(f.getAbsolutePath(), pattern)){ 
							resultFile = f.getName();
							break;
						}
					}
				}
			}
		}
	}

	/**
	 * Search text in file by pattern
	 * @param fileName - input file name
	 * @param pattern - pattern for search
	 * @return
	 */
	public static boolean textFind(String fileName, String pattern){

		StringBuilder sb = new StringBuilder();

		try {
			BufferedReader reader = new BufferedReader(new FileReader(fileName));

			while (reader.ready()) {
				//Read line-by-line directly
				sb.append(reader.readLine());
			}
		}
		catch(IOException ex) {
			ex.printStackTrace();
		}

		String fileText = sb.toString();

		if (fileText.indexOf(pattern) == -1)
			return false;
		else return true;
	}

	/**
	 * Search in mask file pattern text 
	 * @param dir - current directory
	 * @param _fileMask - file mask
	 * @param _pattern - text pattern
	 * @return true if find, null if not find
	 */
	public static String getFileByMask(String dir, String _fileMask, String _pattern) 
	{
		fileMask = _fileMask;
		pattern = _pattern;
		resultFile = null;

		File currDir = new File (dir);
		listFilesInDirectory(currDir);

		return resultFile;
	}
}
